package com.zbkj.service.service.integral.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.category.Category;
import com.zbkj.common.model.integral.IntegralProduct;
import com.zbkj.common.model.product.*;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.StoreProductAttrValueRequest;
import com.zbkj.common.request.StoreProductStockRequest;
import com.zbkj.common.request.integral.IntegralProductRequest;
import com.zbkj.common.request.integral.IntegralProductSearchRequest;
import com.zbkj.common.response.StoreProductAttrValueResponse;
import com.zbkj.common.response.StoreProductResponse;
import com.zbkj.common.response.integral.IntegralProductDetailH5Response;
import com.zbkj.common.response.integral.IntegralProductDetailResponse;
import com.zbkj.common.response.integral.ProductAttrResponse;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.service.dao.IntegralProductDao;
import com.zbkj.service.delete.ProductUtils;
import com.zbkj.service.service.*;
import com.zbkj.service.service.integral.IntegralProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Mr.Zhang
 * @description IntegralProductServiceImpl 接口实现
 * @date 2021-07-20
 */
@Service
@Slf4j
public class IntegralProductServiceImpl extends ServiceImpl<IntegralProductDao, IntegralProduct> implements IntegralProductService {

    @Resource
    private IntegralProductDao dao;

//    @Resource
//    private StoreProductDao productDao;

    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private ProductUtils productUtils;
    @Autowired
    private StoreProductAttrService attrService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;

    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;

    @Autowired
    private StoreProductRelationService storeProductRelationService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StoreProductService storeProductService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<IntegralProduct>
     * @author Mr.Zhang
     * @since 2021-07-20
     */
    @Override
    public List<IntegralProduct> getList(IntegralProductSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 IntegralProduct 类的多条件查询
        LambdaQueryWrapper<IntegralProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(IntegralProduct::getSort);
        if (StringUtils.isNotEmpty(request.getProductName())) {
            lambdaQueryWrapper.like(IntegralProduct::getProductName, request.getProductName());
        }
        //是否开启
        if (request.getIsShowActive()) {
            lambdaQueryWrapper.eq(IntegralProduct::getIsShow, request.getIsShow());
        }
        if (ObjectUtil.isNotNull(request.getCateId()) && request.getCateId() > 0) {
            //查找当前类下的所有子类
            List<Category> childVoListByPid = categoryService.getChildVoListByPid(request.getCateId());
            List<Integer> categoryIdList = childVoListByPid.stream().map(Category::getId).collect(Collectors.toList());
            categoryIdList.add(request.getCateId());
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", (ArrayList<Integer>) categoryIdList));
        }

        List<IntegralProduct> integralProductList = dao.selectList(lambdaQueryWrapper);
//        if (CollectionUtil.isNotEmpty(integralProductList)) {
//            compareProductInfo(integralProductList);
//        }
        return integralProductList;
    }

    public void compareProductInfo(List<IntegralProduct> integralProducts) {
        List<Integer> productIds = integralProducts.stream().map(IntegralProduct::getProductId).collect(Collectors.toList());
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(StoreProduct::getId, productIds);
        List<StoreProduct> productList = storeProductService.list(lambdaQueryWrapper);
        Map<Integer, StoreProduct> productMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, product -> product));
        integralProducts.forEach(integralProduct -> {
//            integralProduct.setProduct(productMap.get(integralProduct.getProductId()));
        });
    }

    private boolean checkIntegralProductExist(Integer productId) {
        LambdaQueryWrapper<IntegralProduct> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(IntegralProduct::getProductId, productId);
        List<IntegralProduct> integralProducts = dao.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(integralProducts)) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addProduct(IntegralProductRequest productRequest) {
        if (checkIntegralProductExist(productRequest.getProductId())) {
            throw new CrmebException("当前商品已经存在积分商品中");
        }
        try {
            IntegralProduct integralProduct = new IntegralProduct();
            BeanUtils.copyProperties(productRequest, integralProduct);
            boolean singleIntegral = true;
            if (ObjectUtil.isNotNull(integralProduct.getType())
                    &&integralProduct.getType().equals(0)) {
                singleIntegral = true;
            } else {
                singleIntegral = false;
            }
            StoreProduct product = storeProductService.getById(integralProduct.getProductId());

            //主图
            integralProduct.setImage(systemAttachmentService.clearPrefix(productRequest.getImage()));

            //轮播图
            integralProduct.setSliderImage(systemAttachmentService.clearPrefix(productRequest.getSlider_image()));


            //计算价格
            productUtils.calcPriceForAttrValuesIntegral(productRequest, integralProduct,singleIntegral);
            //todo 增加积分商品的商品属性
            //保存数据
            boolean save = save(integralProduct);
            if (productRequest.getSpecType()) { // 多属性
                if (null != productRequest.getAttr() && productRequest.getAttr().size() > 0) {
                    productRequest.getAttr().forEach(e -> {
                        e.setId(null);
                        e.setProductId(integralProduct.getId());
                        e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
                        e.setType(Constants.PRODUCT_TYPE_INTEGRAL);
                    });
                    boolean attrAddResult = attrService.saveBatch(productRequest.getAttr());
                    if (!attrAddResult) throw new CrmebException("新增属性名失败");
                }
            }
            else { // 单属性
                StoreProductAttr singleAttr = new StoreProductAttr();
                singleAttr.setProductId(integralProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(Constants.PRODUCT_TYPE_INTEGRAL);
                boolean attrAddResult = attrService.save(singleAttr);
                if (!attrAddResult) throw new CrmebException("新增属性名失败");
//                StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
//                BigDecimal commissionL1 = BigDecimal.ZERO;
//                BigDecimal commissionL2 = BigDecimal.ZERO;
//                if (productRequest.getAttrValue().size() > 0) {
//                    commissionL1 = null != productRequest.getAttrValue().get(0).getBrokerage() ?
//                            productRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
//                    commissionL2 = null != productRequest.getAttrValue().get(0).getBrokerageTwo() ?
//                            productRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
//                }
//
//                singleAttrValue.setProductId(integralProduct.getId()).setStock(integralProduct.getStock()).setSuk("默认")
//                        .setSales(integralProduct.getSales()).setPrice(integralProduct.getPrice())
//                        .setImage(systemAttachmentService.clearPrefix(integralProduct.getImage()))
//                        .setCost(integralProduct.getCost())
//                        .setIntegralPrice(integralProduct.getIntegralPrice())
//                        .setOtPrice(integralProduct.getOtPrice()).setBrokerage(commissionL1).setBrokerageTwo(commissionL2)
//                        .setType(Constants.PRODUCT_TYPE_INTEGRAL);
//                singleAttrValue.setQuota(productRequest.getAttrValue().get(0).getQuota());
//                singleAttrValue.setQuotaShow(singleAttrValue.getQuota());
//                if(singleIntegral){
//                    singleAttrValue.setPrice(BigDecimal.ZERO);
//                }
//                boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
//                if (!saveOrUpdateResult) throw new CrmebException("新增属性详情失败");
            }
            if (null != productRequest.getAttrValue() && productRequest.getAttrValue().size() > 0) {
                // 批量设置attrValues对象的商品id
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = productRequest.getAttrValue();
                storeProductAttrValuesRequest.forEach(e -> {
                    e.setProductId(integralProduct.getId());
                });
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    //设置sku字段
                    if (null == attrValuesRequest.getAttrValue()) {
                        break;
                    }
                    List<String> skuList = new ArrayList<>();
                    LinkedHashMap<String, String> linkedHashMap = JSONObject.parseObject(attrValuesRequest.getAttrValue()
                            , LinkedHashMap.class, Feature.OrderedField);

                    for (Map.Entry<String, String> vo : linkedHashMap.entrySet()) {
                        skuList.add(vo.getValue());
                        spav.setSuk(String.join(",", skuList));
                    }
                    spav.setQuotaShow(spav.getQuota());
                    spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    spav.setType(Constants.PRODUCT_TYPE_INTEGRAL);
                    spav.setId(null);
                    if(singleIntegral){
                        spav.setPrice(BigDecimal.ZERO);
                    }
                    storeProductAttrValues.add(spav);
                }
                // 保存属性
                if (storeProductAttrValues.size() > 0) {
                    boolean saveOrUpdateResult = storeProductAttrValueService.saveOrUpdateBatch(storeProductAttrValues);
                    StoreProductAttrResult attrResult = new StoreProductAttrResult(
                            0,
                            integralProduct.getId(),
                            systemAttachmentService.clearPrefix(JSON.toJSONString(productRequest.getAttrValue())),
                            DateUtil.getNowTime(), Constants.PRODUCT_TYPE_INTEGRAL);
                    storeProductAttrResultService.save(attrResult);
                    if (!saveOrUpdateResult) throw new CrmebException("新增属性详情失败");
                }
            }
            // 处理富文本
            StoreProductDescription spd = new StoreProductDescription(
                    integralProduct.getId(), productRequest.getContent().length() > 0
                    ? systemAttachmentService.clearPrefix(productRequest.getContent()) : "", Constants.PRODUCT_TYPE_INTEGRAL);
            storeProductDescriptionService.deleteByProductId(spd.getProductId(), Constants.PRODUCT_TYPE_INTEGRAL);
            storeProductDescriptionService.save(spd);

            return save;
        } catch (BeansException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public Boolean operationStock(Integer integralProductId, Integer num, String type) {
        UpdateWrapper<IntegralProduct> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
//            updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
        }
        if (type.equals("sub")) {
            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
//            updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
            // 扣减时加乐观锁保证库存不为负
            updateWrapper.last(StrUtil.format(" and (stock - {} >= 0)", num));
        }
        updateWrapper.eq("id", integralProductId);
        boolean update = update(updateWrapper);
        if (!update) {
            throw new CrmebException("更新砍价商品库存失败,商品id = " + integralProductId);
        }
        return update;
    }

    @Override
    public IntegralProductDetailResponse detail(Integer integralProductId) {
        IntegralProductDetailResponse integralProductDetailResponse = new IntegralProductDetailResponse();
        IntegralProduct integralProduct = getById(integralProductId);
        if (ObjectUtil.isNull(integralProduct)) {
            throw new CrmebException("未找到对应积分商品信息");
        }
        StoreProductDescription sd = storeProductDescriptionService.getOne(
                new LambdaQueryWrapper<StoreProductDescription>()
                        .eq(StoreProductDescription::getProductId, integralProduct.getId())
                        .eq(StoreProductDescription::getType, Constants.PRODUCT_TYPE_INTEGRAL));
        if (ObjectUtil.isNotNull(sd)) {
            integralProduct.setContent(StrUtil.isBlank(sd.getDescription()) ? "" : sd.getDescription());
        }

        integralProductDetailResponse.setIntegralProduct(integralProduct);

        // 获取商品规格
        StoreProductAttr spaPram = new StoreProductAttr();
        spaPram.setProductId(integralProduct.getId()).setType(Constants.PRODUCT_TYPE_INTEGRAL);
        List<StoreProductAttr> attrList = attrService.getByEntity(spaPram);
        // 根据制式设置attr属性
        List<ProductAttrResponse> skuAttr = getSkuAttr(attrList);
        integralProductDetailResponse.setAttr(attrList);
        // 根据制式设置sku属性
        HashMap<String, Object> skuMap = MapUtil.newHashMap();
        // 获取主商品sku
        StoreProductAttrValue spavPram = new StoreProductAttrValue();
        spavPram.setProductId(integralProduct.getProductId()).setType(Constants.PRODUCT_TYPE_NORMAL);
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getByEntity(spavPram);
        // 获取积分商品sku
        StoreProductAttrValue spavPram1 = new StoreProductAttrValue();
        spavPram1.setProductId(integralProduct.getId()).setType(Constants.PRODUCT_TYPE_INTEGRAL);
        List<StoreProductAttrValue> integralAttrValues = storeProductAttrValueService.getByEntity(spavPram1);

        integralProductDetailResponse.setAttrValue(integralAttrValues);
        for (int i = 0; i < storeProductAttrValues.size(); i++) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            StoreProductAttrValue productAttrValue = storeProductAttrValues.get(i);
            List<StoreProductAttrValue> valueList = integralAttrValues.stream().filter(e -> {
                return productAttrValue.getSuk().equals(e.getSuk());
            }).collect(Collectors.toList());
            if (CollUtil.isEmpty(valueList)) {
                BeanUtils.copyProperties(productAttrValue, atr);
            } else {
                BeanUtils.copyProperties(valueList.get(0), atr);
            }
            skuMap.put(atr.getSuk(), atr);
        }
        List<HashMap<String, Object>> attrValues = new ArrayList<>();
        integralAttrValues.forEach(integralAttrValue -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", integralAttrValue.getId());
            map.put("productId", integralAttrValue.getProductId());
            map.put("suk", integralAttrValue.getSuk());
            map.put("stock", integralAttrValue.getStock());
            map.put("sales", integralAttrValue.getSales());
            map.put("price", integralAttrValue.getPrice());
            map.put("integralPrice", integralAttrValue.getIntegralPrice());
            map.put("image", integralAttrValue.getImage());
            map.put("unique", integralAttrValue.getUnique());
            map.put("cost", integralAttrValue.getCost());
            map.put("barCode", integralAttrValue.getBarCode());
            map.put("otPrice", integralAttrValue.getOtPrice());
            map.put("weight", integralAttrValue.getWeight());
            map.put("volume", integralAttrValue.getVolume());
            map.put("brokerage", integralAttrValue.getBrokerage());
            map.put("brokerageTwo", integralAttrValue.getBrokerageTwo());
            map.put("type", integralAttrValue.getType());
            map.put("quota", integralAttrValue.getQuota());
            map.put("quotaShow", integralAttrValue.getQuotaShow());
            map.put("attrValue", JSON.parse(integralAttrValue.getAttrValue(), Feature.OrderedField));
//            String currentSku = storeProductAttrValues.get(i).getSuk();
//            String[] skus = integralAttrValues.getSuk().split(",");
//            for (int k = 0; k < skus.length; k++) {
            map.put("value" + 0, integralAttrValue.getSuk());
//            }
            attrValues.add(map);
        });

        integralProductDetailResponse.setAttrValues(attrValues);
        // 用户收藏、分销返佣
        User user = userService.getInfo();
        if (ObjectUtil.isNotNull(user)) {
            // 查询用户是否收藏收藏
            user = userService.getInfo();
            integralProductDetailResponse.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), integralProduct.getProductId(), false).size() > 0);
        } else {
            integralProductDetailResponse.setUserCollect(false);
        }
        return integralProductDetailResponse;
    }

    @Override
    public IntegralProductDetailH5Response detailH5(Integer integralProductId) {

        IntegralProductDetailH5Response integralProductDetailH5Response = new IntegralProductDetailH5Response();
        IntegralProduct integralProduct = getById(integralProductId);
        if (ObjectUtil.isNull(integralProduct)) {
            throw new CrmebException("未找到对应积分商品信息");
        }
        StoreProductDescription sd = storeProductDescriptionService.getOne(
                new LambdaQueryWrapper<StoreProductDescription>()
                        .eq(StoreProductDescription::getProductId, integralProduct.getId())
                        .eq(StoreProductDescription::getType, Constants.PRODUCT_TYPE_INTEGRAL));
        if (ObjectUtil.isNotNull(sd)) {
            integralProduct.setContent(StrUtil.isBlank(sd.getDescription()) ? "" : sd.getDescription());
        }

        integralProductDetailH5Response.setIntegralProduct(integralProduct);

        // 获取商品规格
        StoreProductAttr spaPram = new StoreProductAttr();
        spaPram.setProductId(integralProduct.getId()).setType(Constants.PRODUCT_TYPE_INTEGRAL);
        List<StoreProductAttr> attrList = attrService.getByEntity(spaPram);
        // 根据制式设置attr属性
        List<ProductAttrResponse> skuAttr = getSkuAttr(attrList);
        integralProductDetailH5Response.setProductAttr(skuAttr);
        // 根据制式设置sku属性
        HashMap<String, Object> skuMap = MapUtil.newHashMap();
        // 获取主商品sku
        StoreProductAttrValue spavPram = new StoreProductAttrValue();
        spavPram.setProductId(integralProduct.getProductId()).setType(Constants.PRODUCT_TYPE_NORMAL);
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getByEntity(spavPram);
        // 获取积分商品sku
        StoreProductAttrValue spavPram1 = new StoreProductAttrValue();
        spavPram1.setProductId(integralProduct.getId()).setType(Constants.PRODUCT_TYPE_INTEGRAL);
        List<StoreProductAttrValue> integralAttrValues = storeProductAttrValueService.getByEntity(spavPram1);

        integralProductDetailH5Response.setProductAttr(skuAttr);
        for (int i = 0; i < storeProductAttrValues.size(); i++) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            StoreProductAttrValue productAttrValue = storeProductAttrValues.get(i);
            List<StoreProductAttrValue> valueList = integralAttrValues.stream().filter(e -> {
                return productAttrValue.getSuk().equals(e.getSuk());
            }).collect(Collectors.toList());
            if (CollUtil.isEmpty(valueList)) {
                BeanUtils.copyProperties(productAttrValue, atr);
            } else {
                BeanUtils.copyProperties(valueList.get(0), atr);
                skuMap.put(atr.getSuk(), atr);
            }
        }
        integralProductDetailH5Response.setProductValue(skuMap);

        //设置规格的最小价格起
        priceMinInfo(storeProductAttrValues,integralProductDetailH5Response);

        // 用户收藏、分销返佣
        User user = userService.getInfo();
        if (ObjectUtil.isNotNull(user)) {
            // 查询用户是否收藏收藏
            user = userService.getInfo();
            integralProductDetailH5Response.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), integralProduct.getProductId(), false).size() > 0);
        } else {
            integralProductDetailH5Response.setUserCollect(false);
        }
        return integralProductDetailH5Response;
    }


    private  void priceMinInfo(List<StoreProductAttrValue> storeProductAttrValues,IntegralProductDetailH5Response detailH5Response){

        BigDecimal minPrice=new BigDecimal(0);
        Integer minPriceIntegral=0;
        Integer minIntegralPrice=0;
        for(StoreProductAttrValue attrValue: storeProductAttrValues){
            if(attrValue.getPrice().intValue()==0){
                if(minIntegralPrice==0){
                    minIntegralPrice=attrValue.getIntegralPrice();
                }else{
                    if(attrValue.getIntegralPrice()<minIntegralPrice){
                        minIntegralPrice=attrValue.getIntegralPrice();
                    }
                }
            }else{
                if(minPrice.intValue()==0){
                    minPriceIntegral=attrValue.getIntegralPrice();
                    minPrice=attrValue.getPrice();
                }else{
                    if(attrValue.getPrice().compareTo(minPrice)<0){
                        minPrice=attrValue.getPrice();
                        minPriceIntegral=attrValue.getIntegralPrice();
                    }
                }
            }
        }
        if(minPrice.intValue()==0){
            detailH5Response.getIntegralProduct().setMinPrice(null);
        }else{
            detailH5Response.getIntegralProduct().setMinPrice(minPrice+"+"+minIntegralPrice);
        }
        if(minIntegralPrice==0){
            detailH5Response.getIntegralProduct().setMinIntegralPrice(null);
        }else{
            detailH5Response.getIntegralProduct().setIntegralPrice(minIntegralPrice);
        }
    }

    @Override
    public Boolean stockAddRedis(StoreProductStockRequest stockRequest) {
        String _productString = JSON.toJSONString(stockRequest);
        redisUtil.lPush(Constants.PRODUCT_INTEGRAL_STOCK_UPDATE, _productString);
        return true;
    }

    @Override
    public boolean updateShow(Integer integralProductId, boolean isShow) {
        LambdaUpdateWrapper<IntegralProduct> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(IntegralProduct::getIsShow, isShow);
        updateWrapper.eq(IntegralProduct::getId, integralProductId);
        return update(updateWrapper);
    }

    @Override
    public boolean update(IntegralProductRequest productRequest) {
        try {
            IntegralProduct integralProduct = new IntegralProduct();
            BeanUtils.copyProperties(productRequest, integralProduct);
            StoreProduct product = storeProductService.getById(integralProduct.getProductId());
            boolean singleIntegral = true;
            if (ObjectUtil.isNotNull(integralProduct.getType())
                    &&integralProduct.getType().equals(0)) {
                singleIntegral = true;
            } else {
                singleIntegral = false;
            }
            //主图
            integralProduct.setImage(systemAttachmentService.clearPrefix(productRequest.getImage()));

            //轮播图
            integralProduct.setSliderImage(systemAttachmentService.clearPrefix(productRequest.getSlider_image()));


            //计算价格
            productUtils.calcPriceForAttrValuesIntegral(productRequest, integralProduct,singleIntegral);
            //todo 增加积分商品的商品属性

//保存数据
            boolean update = updateById(integralProduct);
            // 对attr表做全量更新，删除原有数据保存现有数据
            attrService.removeByProductId(productRequest.getId(), Constants.PRODUCT_TYPE_INTEGRAL);
            storeProductAttrValueService.removeByProductId(productRequest.getId(), Constants.PRODUCT_TYPE_INTEGRAL);
            if (productRequest.getSpecType()) { // 多属性
                productRequest.getAttr().forEach(e -> {
                    e.setId(null);
                    e.setProductId(integralProduct.getId());
                    e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
                    e.setType(Constants.PRODUCT_TYPE_INTEGRAL);
                });
                boolean attrAddResult = attrService.saveOrUpdateBatch(productRequest.getAttr());
                if (!attrAddResult) throw new CrmebException("新增属性名失败");
            } else { // 单属性
                StoreProductAttr singleAttr = new StoreProductAttr();
                singleAttr.setProductId(integralProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(Constants.PRODUCT_TYPE_INTEGRAL);
                boolean attrAddResult = attrService.save(singleAttr);
                if (!attrAddResult) throw new CrmebException("新增属性名失败");
                StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
                BigDecimal commissionL1 = BigDecimal.ZERO;
                BigDecimal commissionL2 = BigDecimal.ZERO;
                if (productRequest.getAttrValue().size() > 0) {
                    commissionL1 = null != productRequest.getAttrValue().get(0).getBrokerage() ?
                            productRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                    commissionL2 = null != productRequest.getAttrValue().get(0).getBrokerageTwo() ?
                            productRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
                }
                singleAttrValue.setIntegralPrice(productRequest.getAttrValue().get(0).getIntegralPrice());
                singleAttrValue.setQuota(productRequest.getAttrValue().get(0).getQuota());
                singleAttrValue.setQuotaShow(productRequest.getAttrValue().get(0).getQuota());
                singleAttrValue.setProductId(integralProduct.getId()).setStock(integralProduct.getStock()).setSuk("默认")
                        .setSales(integralProduct.getSales()).setPrice(integralProduct.getPrice())
                        .setImage(systemAttachmentService.clearPrefix(integralProduct.getImage()))
                        .setCost(integralProduct.getCost())
                        .setOtPrice(integralProduct.getOtPrice()).setBrokerage(commissionL1).setBrokerageTwo(commissionL2)
                        .setType(Constants.PRODUCT_TYPE_INTEGRAL);
                if(singleIntegral){
                    singleAttrValue.setPrice(BigDecimal.ZERO);
                }
                boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
                if (!saveOrUpdateResult) throw new CrmebException("新增属性详情失败");
            }
            if (null != productRequest.getAttrValue() && productRequest.getAttrValue().size() > 0) {
                // 批量设置attrValues对象的商品id
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = productRequest.getAttrValue();
                storeProductAttrValuesRequest.forEach(e -> {
                    e.setProductId(integralProduct.getId());
                });
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    //设置sku字段
                    if (null == attrValuesRequest.getAttrValue()) {
                        break;
                    }
                    List<String> skuList = new ArrayList<>();
                    LinkedHashMap<String, String> linkedHashMap = JSONObject.parseObject(attrValuesRequest.getAttrValue()
                            , LinkedHashMap.class, Feature.OrderedField);

                    for (Map.Entry<String, String> vo : linkedHashMap.entrySet()) {
                        skuList.add(vo.getValue());
                        spav.setSuk(String.join(",", skuList));
                    }
                    spav.setQuotaShow(spav.getQuota());
                    spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    spav.setType(Constants.PRODUCT_TYPE_INTEGRAL);
                    spav.setId(null);
                    if(singleIntegral){
                        spav.setPrice(BigDecimal.ZERO);
                    }
                    storeProductAttrValues.add(spav);
                }
                // 保存属性
                if (storeProductAttrValues.size() > 0) {
                    boolean saveOrUpdateResult = storeProductAttrValueService.saveOrUpdateBatch(storeProductAttrValues);
                    // attrResult整存整取，不做更新
                    storeProductAttrResultService.deleteByProductId(integralProduct.getId(), Constants.PRODUCT_TYPE_INTEGRAL);

                    StoreProductAttrResult attrResult = new StoreProductAttrResult(
                            0,
                            integralProduct.getId(),
                            systemAttachmentService.clearPrefix(JSON.toJSONString(productRequest.getAttrValue())),
                            DateUtil.getNowTime(), Constants.PRODUCT_TYPE_INTEGRAL);
                    storeProductAttrResultService.save(attrResult);
                    if (!saveOrUpdateResult) throw new CrmebException("新增属性详情失败");
                }
            }
            // 处理富文本
            StoreProductDescription spd = new StoreProductDescription(
                    integralProduct.getId(), productRequest.getContent().length() > 0
                    ? systemAttachmentService.clearPrefix(productRequest.getContent()) : "", Constants.PRODUCT_TYPE_INTEGRAL);
            storeProductDescriptionService.deleteByProductId(spd.getProductId(), Constants.PRODUCT_TYPE_INTEGRAL);
            storeProductDescriptionService.save(spd);

            return update;
        } catch (BeansException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public void consumeProductStock() {
        String redisKey = Constants.PRODUCT_INTEGRAL_STOCK_UPDATE;
        Long size = redisUtil.getListSize(redisKey);
        log.info("StoreProductServiceImpl.doProductStock | size:" + size);
        if (size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redisUtil.getRightPop(redisKey, 10L);
            if (null == data) {
                continue;
            }
            try {
                StoreProductStockRequest storeProductStockRequest =
                        com.alibaba.fastjson.JSONObject.toJavaObject(com.alibaba.fastjson.JSONObject.parseObject(data.toString()), StoreProductStockRequest.class);
                boolean result = doProductStock(storeProductStockRequest);
                if (!result) {
                    redisUtil.lPush(redisKey, data);
                }
            } catch (Exception e) {
                redisUtil.lPush(redisKey, data);
            }
        }
    }

    private boolean doProductStock(StoreProductStockRequest storeProductStockRequest) {
        IntegralProduct integralProduct = getById(storeProductStockRequest.getIntegralProductId());
        List<StoreProductAttrValue> existAttr =
                storeProductAttrValueService.getListByProductIdAndAttrId(
                        storeProductStockRequest.getIntegralProductId()
                        , storeProductStockRequest.getAttrId().toString()
                        , storeProductStockRequest.getType());
        if (ObjectUtil.isNull(integralProduct) || ObjectUtil.isNull(existAttr)) {
            log.info("库存修改任务未获取到商品信息" + JSON.toJSONString(storeProductStockRequest));
            return true;

        }
        // 回滚商品库存/销量 并更新
        boolean isPlus = storeProductStockRequest.getOperationType().equals("add");
        int productStock = isPlus ? integralProduct.getStock() + storeProductStockRequest.getNum() : integralProduct.getStock() - storeProductStockRequest.getNum();
        integralProduct.setStock(productStock);
        integralProduct.setSales(integralProduct.getSales() - storeProductStockRequest.getNum());
        updateById(integralProduct);
        // 回滚sku库存
        for (StoreProductAttrValue attrValue : existAttr) {
            int productAttrStock = isPlus ? attrValue.getStock() + storeProductStockRequest.getNum() : attrValue.getStock() - storeProductStockRequest.getNum();
            attrValue.setStock(productAttrStock);
            attrValue.setSales(attrValue.getSales() - storeProductStockRequest.getNum());
//            attrValue.setQuota(attrValue.getQuota() + storeProductStockRequest.getNum()); 回滚限购总数
            storeProductAttrValueService.updateById(attrValue);

        }

        // 商品本身库存回滚
        // StoreProductStockRequest 创建次对象调用商品扣减库存实现扣减上本本身库存
        StoreProductResponse existProductLinkedSeckill = storeProductService.getByProductId(storeProductStockRequest.getProductId());
        for (StoreProductAttrValueResponse attrValueResponse : existProductLinkedSeckill.getAttrValue()) {
            if (attrValueResponse.getSuk().equals(storeProductStockRequest.getSuk())) {
                StoreProductStockRequest r = new StoreProductStockRequest()
                        .setAttrId(attrValueResponse.getId())
                        .setNum(storeProductStockRequest.getNum())
                        .setOperationType("add")
                        .setProductId(storeProductStockRequest.getProductId())
                        .setType(Constants.PRODUCT_TYPE_INTEGRAL)
                        .setSuk(storeProductStockRequest.getSuk());
                storeProductService.doProductStock(r);
            }
        }

        return true;
    }

    /**
     * 设置制式结构给attr属性
     *
     * @param attrList attr列表
     * @return List<MyRecord>
     */
    private List<ProductAttrResponse> getSkuAttr(List<StoreProductAttr> attrList) {
        List<ProductAttrResponse> attrResponseList = new ArrayList<>();
        for (StoreProductAttr attr : attrList) {
            ProductAttrResponse attrResponse = new ProductAttrResponse();
            attrResponse.setProductId(attr.getProductId());
            attrResponse.setAttrName(attr.getAttrName());
            attrResponse.setType(attr.getType());
            List<String> attrValues = new ArrayList<>();
            String trimAttr = attr.getAttrValues()
                    .replace("[", "")
                    .replace("]", "");
            if (attr.getAttrValues().contains(",")) {
                attrValues = Arrays.asList(trimAttr.split(","));
            } else {
                attrValues.add(trimAttr);
            }
            attrResponse.setAttrValues(attrValues);
            attrResponseList.add(attrResponse);
        }
        return attrResponseList;
    }
    public static void main(String[] args) {
        StoreProductAttrValue storeProductAttrValue=new StoreProductAttrValue();
        storeProductAttrValue.setPrice(new BigDecimal(0));
        storeProductAttrValue.setIntegralPrice(100);
        StoreProductAttrValue storeProductAttrValue1=new StoreProductAttrValue();
        storeProductAttrValue1.setPrice(new BigDecimal(0));
        storeProductAttrValue1.setIntegralPrice(200);
        StoreProductAttrValue storeProductAttrValue2=new StoreProductAttrValue();
        storeProductAttrValue2.setPrice(new BigDecimal(30));
        storeProductAttrValue2.setIntegralPrice(150);
        StoreProductAttrValue storeProductAttrValue3=new StoreProductAttrValue();
        storeProductAttrValue3.setPrice(new BigDecimal(50));
        storeProductAttrValue3.setIntegralPrice(200);
        List<StoreProductAttrValue> attrValues=new ArrayList<>();
        attrValues.add(storeProductAttrValue);
        attrValues.add(storeProductAttrValue1);
        attrValues.add(storeProductAttrValue2);
        attrValues.add(storeProductAttrValue3);
//        priceMinInfo(attrValues);

    }
}

